/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tolls;

import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import model.DBManager;
import roles.EditRoleForm;
import users.EditUserForm;

/**
 *@author Aggelos
 * Avgeros,
 * Karagiannis,
 * Katselas,
 * Kofidou,
 * Manolopoulou
 */
public class CollectTollForm extends javax.swing.JFrame {
    
    Double balance;
    EntityManager em;
    
    /**
     * Creates new form CollectTollForm
     */
    public CollectTollForm() {
        em=DBManager.em; 
        em.getTransaction().begin();
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        regNum = new javax.swing.JTextField();
        button1 = new javax.swing.JButton();
        cardId = new javax.swing.JTextField();
        cardIdLabel = new javax.swing.JLabel();
        regNumLabel = new javax.swing.JLabel();
        button2 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        balanceLabel = new javax.swing.JLabel();
        balanceTextField = new javax.swing.JTextField();
        button3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        button1.setText("ΔΙΕΛΕΥΣΗ");
        button1.setEnabled(false);
        button1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button1ActionPerformed(evt);
            }
        });

        cardIdLabel.setText("Αρ. Κάρτας: ");

        regNumLabel.setText("Αρ. Κυκλοφορίας: ");

        button2.setText("ΠΛΗΡΩΜΗ");
        button2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button2ActionPerformed(evt);
            }
        });

        balanceLabel.setText("Υπόλοιπο Κάρτας: ");

        button3.setText("Έλεγχος Ταυτότητας");
        button3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(regNumLabel)
                                    .addComponent(cardIdLabel))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(regNum, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cardId, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(29, 29, 29)
                                        .addComponent(button3))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(button1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(button2))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(balanceLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(balanceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 445, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(regNumLabel)
                    .addComponent(regNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cardIdLabel)
                    .addComponent(cardId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(button3))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(balanceLabel)
                    .addComponent(balanceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 138, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(button1)
                    .addComponent(button2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void button2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button2ActionPerformed
        // TODO add your handling code here:
        if (balanceTextField.getText()!=null){
            PaymentForm pf=new PaymentForm(em,cardId.getText(),regNum.getText(),balanceTextField.getText());
            pf.setVisible(true);
        }
        else{
            JOptionPane.showMessageDialog(this,"Δεν μπορεί να πραγματοποιηθεί πληρωμή πριν βρεθεί το όχημα!"); 
        }
    }//GEN-LAST:event_button2ActionPerformed

    private void button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button1ActionPerformed
        // TODO add your handling code here:
        
        int id = Integer.parseInt(cardId.getText());
        double balance = Double.parseDouble(balanceTextField.getText());
        
        // Εύρεση ποσού πληρωμής
        Query query1 = em.createNativeQuery("SELECT AVENUE.PROGRAM_RATE.RATE FROM AVENUE.PROGRAM_RATE, AVENUE.VEHICLE WHERE AVENUE.PROGRAM_RATE.CATEGORY_ID = AVENUE.VEHICLE.CATEGORY_ID AND AVENUE.VEHICLE.CARD_ID = " + id);
        List list1 = query1.getResultList(); 
        double poso=Double.parseDouble(list1.get(0).toString());
        
        // Ενημέρωση υπολοίπου της κάρτας
        em.createNativeQuery("UPDATE AVENUE.CARD c SET c.BALANCE = c.BALANCE - " + poso + " WHERE ID = " + id).executeUpdate();
        
        // Εισαγωγή διέλευσης
        Date date = new Date();
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());
        em.createNativeQuery("INSERT INTO AVENUE.COLLECTION(CARD_ID, PASS_TIMESTAMP,TOLL_COLLECTED) VALUES(" + id +", '" + sqlDate + "', " + poso + ")").executeUpdate();
        
        String message = "Επιτυχής Διέλευση!";
        JOptionPane.showMessageDialog(this, message);
        
        em.getTransaction().commit();
        
        dispose();
        
    }//GEN-LAST:event_button1ActionPerformed

    private void button3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button3ActionPerformed
        // TODO add your handling code here:
        String str1 = regNum.getText();
        String str2 = cardId.getText();
        int id = Integer.parseInt(str2);   
   
        // Ανάκτηση οχήματος
        Query query2 = em.createNativeQuery("SELECT * FROM AVENUE.VEHICLE WHERE  AVENUE.VEHICLE.CARD_ID = " + id + " AND  AVENUE.VEHICLE.REG_NUMBER = '" + str1 + "'");
        List list2 = query2.getResultList();
    
        Query query3 = em.createNativeQuery("SELECT  AVENUE.CARD.BALANCE FROM CARD WHERE  AVENUE.CARD.ID = " + id);
        List list3 = query3.getResultList();  
        if (list2.size()==1){
            String str3 = list3.get(0).toString();
            balanceTextField.setText(str3);
            balance = Double.parseDouble(str3);
            if (balance < 10){
                JOptionPane.showMessageDialog(this,"Προχωρήστε σε Πληρωμή της κάρτας.");
            }
            else{
                button1.setEnabled(true);
            }
        }
        else{
            JOptionPane.showMessageDialog(this,"Λάθος Στοιχεία!");
        }
    }//GEN-LAST:event_button3ActionPerformed

   public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CollectTollForm().setVisible(true);
            }
        });
    } 
    
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel balanceLabel;
    private javax.swing.JTextField balanceTextField;
    private javax.swing.JButton button1;
    private javax.swing.JButton button2;
    private javax.swing.JButton button3;
    private javax.swing.JTextField cardId;
    private javax.swing.JLabel cardIdLabel;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField regNum;
    private javax.swing.JLabel regNumLabel;
    // End of variables declaration//GEN-END:variables


}
